import axios from 'axios'
// import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 300000, // request timeout
  headers: {
    // "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
    'Accept-Language': 'zh_CN',
    'Content-Type': 'application/json; charset=UTF-8'
  }
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      // let testT = "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjYsInVzZXJuYW1lIjoiMTg2ODAzOTA3MjYiLCJzdWIiOiIxODY4MDM5MDcyNiIsImlhdCI6MTc1Mzk1MzM3NSwiZXhwIjoxNzU0NTU4MTc1fQ.4z4tGIezvU8YLyonrIgUPkFV_O9oyqwwH9jYRk-QWjA"
      config.headers['Authorization'] = getToken()
      // config.headers['Authorization'] = testT
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
const no_need_to_backend = ['downloadFile']
service.interceptors.response.use(
  response => {
    const res = response.data

    const file = response.config.headers.no_need_to_transfer_to_the_backend
    // 这个判断是判断是否需要全部返回参数的
    if (no_need_to_backend.includes(file)) {
      return Promise.resolve(response)
    }
    // 直接返回 data 暂时没有其他的需求
    return Promise.resolve(res)
  },
  error => {
    const { status } = error.response
    if (status === 401) {
      store.commit('SET_TOKEN', '')
      store.commit('SET_ROLES', [])
      removeToken()
      resetRouter()
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

export default service
